package com.example.behaviorpattern.observer.impl;

import com.example.behaviorpattern.observer.MyMessage;
import com.example.behaviorpattern.observer.MyObserver;
import com.example.behaviorpattern.observer.MySubject;

import java.util.ArrayList;
import java.util.List;


/**
 * @author yaojianfeng
 */
public class ConcreteSubject implements MySubject {

    private final List<MyObserver> observers = new ArrayList<>();
    // 这里的message是私有的，只能通过setState方法来修改 message的值，其他方法只能访问message的值
    private MyMessage message;

    public void setState(MyMessage message) {
        this.message = message;
        notifyObservers();
    }

    @Override
    public void registerObserver(MyObserver o) {
        observers.add(o);

    }

    @Override
    public void removeObserver(MyObserver o) {
        observers.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (MyObserver observer : observers) {
            observer.update(message);
        }
    }
}
